import { COMMIT_CARD, DELETE_CARD, GET_CARDS } from '@/graphql/card';
import { ICard } from '@/utils/types';
import { useLazyQuery, useMutation, useQuery } from '@apollo/client';
import { message } from 'antd';

export const useCards = (courseId:string) => {
  const { data, loading, refetch } = useQuery(GET_CARDS, {
    variables: {
      courseId,
    },
  });
  return {
    loading,
    data: data?.getCards.data,
    refetch,
  };
};

// 设置lazy，需要手动触发
export const useLazyCards = () => {
  const [get, { data, loading }] = useLazyQuery(GET_CARDS);
  const getCards = (courseId:string) => {
    get({
      variables: {
        courseId,
      },
    });
  };
  return {
    loading,
    data: data?.getCards.data,
    getCards,
  };
};

export const useEditCardInfo = ():[handleEdit: Function, loading: boolean] => {
  const [edit, { loading }] = useMutation(COMMIT_CARD);
  const handleEdit = async (
    id:string,
    courseId:string,
    params:ICard,
    callback:(isReload?:boolean) => void,
  ) => {
    const res = await edit({
      variables: {
        id: id === 'new' ? '' : id,
        courseId,
        params,
      },
    });
    if (res.data.commitCardInfo.code === 200) {
      message.success(res.data.commitCardInfo.message);
      callback(true);
      return;
    }
    message.error(res.data.commitCardInfo.message);
  };
  return [handleEdit, loading];
};

export const useDelCardInfo = ():[handlerDel: Function, loading: boolean] => {
  const [del, { loading }] = useMutation(DELETE_CARD);
  const handlerDel = async (id:string, callback:(isReload?:boolean) => void) => {
    const res = await del({
      variables: {
        id,
      },
    });
    if (res.data.deleteCard.code === 200) {
      message.success(res.data.deleteCard.message);
      callback(true);
      return;
    }
    message.error(res.data.commitCardInfo.message);
  };
  return [handlerDel, loading];
};
